package com.dcy.workflow.dao;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.dcy.common.model.PageModel;
import com.dcy.common.model.PageResult;
import com.dcy.workflow.vo.in.ProcessDefinitionSearchInVO;
import com.dcy.workflow.vo.out.ProcessDefinitionListOutVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.repository.ProcessDefinitionQuery;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author dcy
 * @description 流程实现类
 * @createTime 2022/12/22 9:32
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class ActProcessDao {

    private final RepositoryService repositoryService;

    /**
     * 流程定义分页列表
     *
     * @param processDefinitionSearchInVO
     * @param pageModel
     * @return
     */
    public PageResult<ProcessDefinitionListOutVO> processDefinitionPageList(ProcessDefinitionSearchInVO processDefinitionSearchInVO, PageModel pageModel) {
        PageResult<ProcessDefinitionListOutVO> pageResult = new PageResult<>();
        ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery().orderByProcessDefinitionId().orderByProcessDefinitionVersion().desc();
        if (StrUtil.isNotBlank(processDefinitionSearchInVO.getName())) {
            processDefinitionQuery.processDefinitionNameLike(StrUtil.format("%{}%", processDefinitionSearchInVO.getName()));
        }
        if (StrUtil.isNotBlank(processDefinitionSearchInVO.getKey())) {
            processDefinitionQuery.processDefinitionKeyLike(StrUtil.format("%{}%", processDefinitionSearchInVO.getKey()));
        }
        List<ProcessDefinitionListOutVO> list = new ArrayList<>();
        // 设置首页页码
        PageUtil.setFirstPageNo(1);
        List<ProcessDefinition> processDefinitionList = processDefinitionQuery.listPage(PageUtil.getStart(Convert.toInt(pageModel.getCurrent()), Convert.toInt(pageModel.getSize())), Convert.toInt(pageModel.getSize()));
        long count = processDefinitionQuery.count();
        for (ProcessDefinition processDefinition : processDefinitionList) {
            String deploymentId = processDefinition.getDeploymentId();
            Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult();
            list.add(new ProcessDefinitionListOutVO(processDefinition, deployment));
        }
        // 赋值
        pageResult.setCurrent(pageModel.getCurrent());
        pageResult.setTotal(count);
        pageResult.setSize(pageModel.getSize());
        pageResult.setRecords(list);
        pageResult.setPages(PageUtil.totalPage(Convert.toInt(count), Convert.toInt(pageModel.getSize())));
        return pageResult;
    }

}
